//
//  CustomerPresentingAnimator.swift
//  About me
//
//  Created by Nathan on 4/26/15.
//  Copyright (c) 2015 TAC. All rights reserved.
//

import UIKit
import pop

class CustomerPresentingAnimator: NSObject,UIViewControllerAnimatedTransitioning {
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView                    = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!.view
        fromView?.tintAdjustmentMode     = UIViewTintAdjustmentMode.dimmed
        fromView?.isUserInteractionEnabled = true
        
        let dimmingView             = UIView(frame: (fromView?.bounds)!)
        dimmingView.backgroundColor = UIColor.gray
        dimmingView.layer.opacity   = 0.3
        
//        let recognizer = UITapGestureRecognizer(target: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!, action: #selector(backgroundDidPressed))
//        dimmingView.addGestureRecognizer(recognizer)
        
        let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!.view
//        if UIScreen.main.bounds.size.equalTo(CGSize(width: 320, height: 480)){
//            toView?.frame = CGRect(x: 0, y: 0, width: transitionContext.containerView.bounds.width-50, height: transitionContext.containerView.bounds.height - 60)
//        }
//        else{
//            toView?.frame = CGRect(x: 0, y: 0, width: transitionContext.containerView.bounds.width-50, height: transitionContext.containerView.bounds.height - 100)
//        }

        toView?.center = CGPoint(x: -transitionContext.containerView.center.x, y: transitionContext.containerView.center.y)
        
        transitionContext.containerView.addSubview(toView!)
        transitionContext.containerView.insertSubview(dimmingView, at: 0)

        let positionAnimation              = POPSpringAnimation(propertyNamed: kPOPLayerPositionX)
        positionAnimation?.toValue          = transitionContext.containerView.center.x
        positionAnimation?.springBounciness = 10
        positionAnimation?.completionBlock  = {
            (anim : POPAnimation?,finished : Bool) in
            transitionContext.completeTransition(true)
        }
        
        
        let scaleAnimation              = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
        scaleAnimation?.springBounciness = 20
        scaleAnimation?.fromValue        = NSValue(cgPoint: CGPoint(x:1.2, y:1.4))

        let opacityAnimation            = POPBasicAnimation(propertyNamed: kPOPLayerOpacity)
        opacityAnimation?.toValue        = 0.2
        
        toView?.layer.pop_add(positionAnimation, forKey:"positionAnimation")
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
}
